package com.scrapy.http.html;

import com.scrapy.http.pojo.Joke;
import com.scrapy.until.str.StringUtil;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 分析笑话网页的类
 * Created by wanter on 2016/11/9.
 */
public class AnalysisJokeHtml {
    /**
     * 解析出的笑话放在这个里边
     */
    private Joke joke;
    /**
     * 对笑话存放的html内容
     */
    private String jokeHtml;


    public AnalysisJokeHtml(String jokeHtml) {
        this.jokeHtml = jokeHtml;
        joke = new Joke();
    }

    /**
     *
     * @return 拿到笑话的内容
     */
    public String getJokeContent(){
        String regex = "((<div class=\"content\">)(.*?)(</div></div><div class='page-nav-list'>))";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(this.jokeHtml);
        if (matcher.find()){
            return StringUtil.removeBr(matcher.group(3));

        }
        return "笑话匹配失败";
    }

    /**
     * 拿到作者的名字
     * 是为了拿到作者
     * 的地址
     * @return 笑话作者的姓名
     */
   public String getJokeAuthorName(){
       String regex = "((<h2>)(.*?)(</h2>))";
       Pattern pattern = Pattern.compile(regex);
       Matcher matcher = pattern.matcher(this.jokeHtml);
       if (matcher.find()){
           return StringUtil.removeBr(matcher.group(3));
       }
       return "名字匹配失败";
   }

    public String getJokeAuthorUrl(){
        String regex = "((alt=\""+this.getJokeAuthorName()+"\"/></a><a href=\")(.*?)(\" target=\"_blank\" title=\""+this.getJokeAuthorName()+"\"><h2>))";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(this.jokeHtml);
        if (matcher.find()){
            return  "http://www.qiushibaike.com"+StringUtil.removeBr(matcher.group(3));

        }
        return "作者的地址匹配失败";
    }

    /**
     * 设置笑话的好笑数与评论数
     */
    private void setStats(){
        String regex = "<i class=\"number\">(.*?)</i>";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(this.jokeHtml);
        if (matcher.find()){
            joke.setStatsVote(Integer.parseInt(matcher.group(1)));

        }if (matcher.find()){
            joke.setDash(Integer.parseInt(matcher.group(1)));

        }

    }
    /**
     * 返回joke笑话
     * @return 返回内涵段子本身
     */
    public Joke getJoke() {
        setStats();
        joke.setContent(this.getJokeContent());
        joke.setDate(new Date());
        joke.setAuthorName(this.getJokeAuthorName());
        joke.setAuthorUrl(this.getJokeAuthorUrl());
        return joke;
    }
}
